import React, { Component } from 'react';
import { Tools, Progress } from 'weaver-mobile';
import { renderLoading, TitleUtil } from '../../util'

class Main extends Component {
  constructor (props) {
    super(props)
    this.state = {
      loading: true,
    }
    this.getUpgradeInfo();
    this.timer = setInterval(() => this.getUpgradeInfo(), 5000)
  }

  componentDidMount() {
    TitleUtil.setTitle('')
  }
  
  componentWillUnmount() {
    clearInterval(this.timer);
    TitleUtil.resetEmElement()
  }
  
  getUpgradeInfo = () => {
    Tools.callApi({url: '/api/email/base/emailUpgrade', method: 'GET'}).then(res => {
      const { completedcount, totalcount } = res;
      let percent = (completedcount / totalcount).toFixed(4);
      percent = Math.round(percent * 10000) / 100;
      res.upgrade_status === '1' && clearInterval(this.timer);
      res = {...res, percent}
      this.setState({...res, loading: false})
    })
  }

  render () {
    const preUpgradeCls = 'email-updrage';
    const { upgrade_status, percent, loading } = this.state
    return loading ? renderLoading : (
      <div className={preUpgradeCls}>
        {
          upgrade_status && upgrade_status === '0' && (
            <div className={`${preUpgradeCls}-container`}>
              <Progress type='circle' percent={percent} circleWidth='100%' showInfo />
              <div className='tipinfo'>模块升级中，请稍后进入</div>
            </div>
          )
        }
        {upgrade_status && upgrade_status === '1' && this.props.children}
      </div>
    )
  }
}

export default Main